﻿using Corina.Commands;
using Corina.Common;
using Corina.Win.Helpers;
using Corina.Win.Interface;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;

namespace Corina.Win.ServerHub.Viewmodels
{
    public class MainViewmodel : DataContainer
    {
        public MainViewmodel()
        {
            CheckPublicIPAddress();
            AccountChanged += CurrentAccountChanged;
            ServerStatusChanged += MainViewmodelServerStatusChanged;
        }

        private void MainViewmodelServerStatusChanged(object sender, EventArgs e)
        {
            RaisePropertyChanged(() => CloseCommand);
        }

        private void CurrentAccountChanged(object sender, EventArgs e)
        {
            SelectedViewmodel = null;
            RaisePropertyChanged(() => HomeCommand);
            ComposeAssembly();
            RaisePropertyChanged(() => ContractViewmodels);
        }

        #region Windows Control
        
        public string AppTitle
        {
            get { return "泊银服务器"; }
        }

        public Version ApplicationVersion
        {
            get
            {
                //return Application.ResourceAssembly.GetName(false).Version;
                //return System.Windows.Forms.Application.ProductVersion;
                try
                {
                    return System.Deployment.Application.ApplicationDeployment.CurrentDeployment.CurrentVersion;
                    //return System.Deployment
                }
                catch
                {
                    return Assembly.GetExecutingAssembly().GetName().Version;
                }
            }
        }

        public ContentControl ElementView
        {
            get
            {
                try
                {
                    string template = "default";// ConfigurationManager.AppSettings[ConstKeys.APP_TEMPLATE_KEY];
                    return XamlHelper.LoadXamlFromFile<ContentControl>(System.Windows.Forms.Application.StartupPath + string.Format("\\HomeUI\\{0}.xaml", template));
                }
                catch(Exception ex)
                {
                    ErrorTraceHelper.Trace(ex);
                    return null;
                }
            }
        }

        public ICommand CloseCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return !IsServerRunning; },
                    ExecuteCallback = delegate
                    {
                        Application.Current.Shutdown();
                    }
                };
            }
        }

        public ICommand MinizedCommand
        {
            get
            {
                return new GenericCommand()
                {
                    ExecuteCallback = delegate
                    {
                        Application.Current.MainWindow.WindowState = WindowState.Minimized;
                    }
                };
            }
        }

        public ICommand HomeCommand
        {
            get
            {
                return new GenericCommand()
                {
                    CanExecuteCallback = delegate { return IsValid; },
                    ExecuteCallback = delegate {
                        SelectedViewmodel = null;
                    }
                };
            }
        }
        #endregion

        #region Contract
        [ImportMany(typeof(IView), AllowRecomposition = true)]
        public List<Lazy<IView>> ContractViewmodels { get; set; }

        private Lazy<IView> _selectedViewmodel;
        public Lazy<IView> SelectedViewmodel
        {
            get { return _selectedViewmodel; }
            set
            {
                _selectedViewmodel = value;
                RaisePropertyChanged(() => SelectedViewmodel);
                ViewUrl = SelectedViewmodel == null ? string.Empty : SelectedViewmodel.Value.FullUrl;
                RaisePropertyChanged(() => IsSelectedNull);
                RaisePropertyChanged(() => Icon);
            }
        }

        public string Icon
        {
            get
            {
                return IsSelectedNull || SelectedViewmodel == null ? "ICON_HOME" : SelectedViewmodel.Value.Icon;
            }
        }

        public bool IsSelectedNull
        {
            get
            {
                return string.IsNullOrEmpty(ViewUrl);
            }
        }
        #endregion

        #region Methods
        private bool ComposeAssembly()
        {
            string addins = System.Windows.Forms.Application.StartupPath + @"\Addins\";
            //string tools = System.Windows.Forms.Application.StartupPath + @"\Tools\";
            if (!Directory.Exists(addins))
            {
                Directory.CreateDirectory(addins);
            }
            //if (!Directory.Exists(tools))
            //{
            //    Directory.CreateDirectory(tools);
            //}

            DirectoryCatalog addins_direc = new DirectoryCatalog(addins, "*.dll");
            //DirectoryCatalog tools_direc = new DirectoryCatalog(tools, "*.dll");

            var catalog = new AggregateCatalog();
            catalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
            catalog.Catalogs.Add(addins_direc);
            //catalog.Catalogs.Add(tools_direc);
            var provider = new ComposablePartExportProvider();

            var container = new CompositionContainer(catalog, provider);
            provider.SourceProvider = container;
            var batch = new CompositionBatch();
            batch.AddPart(this);

            try
            {
                container.Compose(batch);
            }
            catch (CompositionException exception)
            {
                Console.WriteLine(exception.ToString());
                return false;
            }
            return true;
        }
        #endregion

        #region PublicIPAddress
        private string _publicIPAddress = "";
        public string PublicIPAddress
        {
            get
            {
                return string.IsNullOrEmpty(_publicIPAddress) ? "未检测" : _publicIPAddress;
            }
            set
            {
                _publicIPAddress = value;
                RaisePropertyChanged(() => PublicIPAddress);
            }
        }

        private void CheckPublicIPAddress()
        {
            WebClient client = new WebClient();
            client.DownloadStringCompleted += GetIPAddressComplered;
            client.DownloadStringAsync(new Uri("http://ifconfig.me/ip"));
        }

        private void GetIPAddressComplered(object sender, DownloadStringCompletedEventArgs e)
        {
            if (e.Error == null)
            {
                PublicIPAddress = RegexHelper.ExtractIPAddress(e.Result);
            }
        }
        #endregion
    }
}
